package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.PlayHistoryListAdapter;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.async.RequestEpisodesTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.LocalVideoEpisode;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.PlayRecordList;
import com.elinkway.infinitemovies.bean.VideoDataBean;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.VideoDetailParser;
import com.elinkway.infinitemovies.http.requestInterface.RequestCommonInterface;
import com.elinkway.infinitemovies.http.requesttask.RequestAlbumInfoTask;
import com.elinkway.infinitemovies.http.requesttask.RequestDoPlayRecordTask;
import com.elinkway.infinitemovies.http.requesttask.RequestUserPlayRecordsTask;
import com.elinkway.infinitemovies.listener.MyOnRefreshListner;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn;
import com.elinkway.infinitemovies.utils.ACache;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PlayHistoryActivity extends BaseSecondaryActivity implements RequestResultListener<VideoDataBean>, OnClickListener {

    public final static String TAG = "PlayHistoryActivity";

    private PullToRefreshListView list;

    private PlayHistoryListAdapter mAdapter;

    private List<PlayRecord> playRecordList = new ArrayList<PlayRecord>();

    private LinearLayout noData;

    private Dialog myProgressDialog;

    private ACache mCache;

    private Handler mHandler;

    private LinearLayout editLayout;


    private TextView allSelect;
    private TextView mConfirm_delete;
    private SharedPreferences mLoginSp;

    /**
     * 当前选择的播放记录
     */
    private PlayRecord currplayRecord = null;

    private RequestVideoDataTask requestVideoDataTask;

    private RequestEpisodesTask requestEpisodesTask;

    private RequestUserPlayRecordsTask mRequestUserPlayRecordsTask;

    private PlayRecordListListener mPlayRecordListListener = new PlayRecordListListener();

    private PublicLoadLayout root;

    private final String PREFIX = "file://";

    private int index = 0;	//分页请求的第一个索引
    private static final int LIMIT = 20;	//每一页的数据数量
    private int total = 0;		//总数
    private boolean hasMore = true;
    private boolean isShowButtom;
    private boolean isFirst = true;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            list.onRefreshComplete();
            super.handleMessage(msg);
        }

    };

    private enum State {
        EDITING, UNEDIT;
    }

    private State currentState = State.UNEDIT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        root = UIs.createPage(this, R.layout.activity_play_history);
        setContentView(root);
        root.setmRefreshData(new PublicLoadLayout.RefreshData() {

            @Override
            public void refreshData() {
                root.loading(false);
                refreshHistoryPage();
            }
        });
        currentPageId = BigDataConstants.PGV_CURRENT_ID_HISTORY;
        initActionBar();
        mCache = ACache.get(this);
        requestVideoDataTask = new RequestVideoDataTask(this);
        requestEpisodesTask = new RequestEpisodesTask(this);
        requestEpisodesTask.setmListener(this);
        myProgressDialog = new Dialog(this, R.style.PlaySrcLoadingDialog);
        myProgressDialog.setContentView(R.layout.loading_dialog);
        myProgressDialog.setCancelable(false);
        mHandler = new Handler();
        initView(root);
        mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
    }

    @Override
    protected void initActionBar(){
        super.initActionBar();
        mTitleTv.setText("播放记录");
        mRightFirstIv.setVisibility(View.GONE);
        mRightSecondIv.setVisibility(View.GONE);
        mRightFirstTv.setText("编辑");
        mRightFirstTv.setVisibility(View.GONE);
        mRightFirstTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (currentState) {
                    case UNEDIT:
                        mAdapter.toggle();
                        mRightFirstTv.setText("完成");
                        currentState = State.EDITING;
                        isShowButtom = true;
                        editLayout.setVisibility(View.VISIBLE);
                        break;
                    case EDITING:
                        mAdapter.toggle();
                        allSelect.setText(R.string.check_all);
                        mConfirm_delete.setText(R.string.delete_up);
                        mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                        playHistroyAllDiselected();
                        mRightFirstTv.setText("编辑");
                        currentState = State.UNEDIT;
                        isShowButtom = false;
                        editLayout.setVisibility(View.INVISIBLE);
                        break;
                }
            }
        });
    }

    private void initView(View view) {

        editLayout = (LinearLayout) view.findViewById(R.id.editlayout);
        allSelect = (TextView) view.findViewById(R.id.all_select);
        mConfirm_delete = (TextView) view.findViewById(R.id.confirm_delete);

        mConfirm_delete.setOnClickListener(this);
        allSelect.setOnClickListener(this);

        list = (PullToRefreshListView) view.findViewById(R.id.play_history_list);
        mAdapter = new PlayHistoryListAdapter(this, playRecordList);
        noData = (LinearLayout) view.findViewById(R.id.play_history_no_data);
        list.setAdapter(mAdapter);
        mAdapter.registerDataSetObserver(new DataSetObserver() {

            @Override
            public void onChanged() {
                if (mAdapter.getCount() == 0) {
                    showNoData();
                }
                super.onChanged();
            }
        });

        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                if (!mAdapter.isEditing) {//非编辑状态
                    currplayRecord = playRecordList.get(position - 1);
                    if (null != currplayRecord) {

                        Map<String, String> dataMap = BigDataApi.createDataMap("0", "","0","-",currplayRecord.getAid(),"-");
                        dataMap.put("rank", position + "");
                        dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_HISTORY);
                        BigDataApi.bigDataCommonReport(dataMap, PlayHistoryActivity.this);

                        String url = currplayRecord.getUrl();
                        if (isLocalUrl(url)) {
                            String fileUrl = url.replace(PREFIX, "").trim();
                            File localFile = new File(fileUrl);
                            //判断当前的URL是否是本地的URL
                            if (null != localFile && localFile.exists()) {
                                PlayData playData = setLocalData(url);
                                jumpToPlayActivity(playData);
                            } else {

                            }
                        } else {
                            onLineLogic(currplayRecord);
                        }
                    }
                } else {//编辑状态
                    mAdapter.setSelectItemChange(position - 1, view);
                    mAdapter.notifyDataSetChanged();
                }

            }
        });
        resetHasMore();
    }

    private PlayData setLocalData(String url) {
        //设置本地视频播放的相关数据
       ArrayList<String> Url = new ArrayList<String>();
        Url.add(url);
        LocalVideoEpisode localVideoEpisode = new LocalVideoEpisode();
        localVideoEpisode.setAid(currplayRecord.getAid());
        localVideoEpisode.setPorder(currplayRecord.getPorder());
        localVideoEpisode.setName(currplayRecord.getName());
        localVideoEpisode.setVt(currplayRecord.getVt());
        localVideoEpisode.setPlay_url(Url);
        ArrayList<LocalVideoEpisode> localVideoEpisodeList = new ArrayList<LocalVideoEpisode>(1);
        localVideoEpisodeList.add(localVideoEpisode);
        PlayData playData = new PlayData();
        //设置播放的是本地的文件
        playData.setIsLocalVideo(true);
        playData.setmLocalDataLists(localVideoEpisodeList);
        playData.setPorder(currplayRecord.getPorder());//知道播的是哪一集播放器
        playData.setAid(currplayRecord.getPorder());
        playData.setmPlayRecord(currplayRecord);

        return playData;
    }

    private void jumpToPlayActivity(PlayData playData) {
        Intent intent = new Intent(PlayHistoryActivity.this, PlayActivitySelfOwn.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(bundle);
        PlayHistoryActivity.this.startActivity(intent);
    }

    private void onLineLogic(PlayRecord record) {
        RealDataApi.RealDataClickReport("",record.getVid(),record.getAid(),"","");
        VideoDetailActivity.launch(PlayHistoryActivity.this, record.getAid(),
                record.getVt(), record.getName(), "", "", "", record.getPorder(),"","");
//        LogUtils.i("playrecord", "请求播放源的列表");
//        if (!requestVideoDataTask.isCancelled()) {
//            requestVideoDataTask.cancel();
//        }
//        requestVideoDataTask.start();

    }

    private void showNoData() {
//		mEditView.setText("编辑");
        list.setVisibility(View.GONE);
        noData.setVisibility(View.VISIBLE);
//		mEditView.setVisibility(View.GONE);
        editLayout.setVisibility(View.INVISIBLE);
        mRightFirstTv.setVisibility(View.GONE);
        supportInvalidateOptionsMenu();
        isFirst = !isFirst;
    }

    private void showList() {
        list.setVisibility(View.VISIBLE);
        noData.setVisibility(View.GONE);
        mRightFirstTv.setVisibility(View.VISIBLE);
        if(isFirst){
            supportInvalidateOptionsMenu();
            isFirst = !isFirst;
        }
    }

    public static void launch(Activity activity) {
        Intent intent = new Intent(activity, PlayHistoryActivity.class);
        UmengEventPoster.postChannelClick(UmengEventPoster.CHANNEL_HISTORY);
        activity.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshHistoryPage();
            }
        }, 50);
        MobclickAgent.onResume(this);
    }

    private void refreshHistoryPage() {
        if(mLoginSp != null && !TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
            index = 0;
            list.setOnRefreshListener(new PlayRecordOnRefreshListener());
            mRequestUserPlayRecordsTask = new RequestUserPlayRecordsTask(PlayHistoryActivity.this, index, LIMIT);
            mRequestUserPlayRecordsTask.setRequestListener(mPlayRecordListListener);
            mRequestUserPlayRecordsTask.start();
        }else{
            List<String> noPosterRecordList = new PlayRecordDao(PlayHistoryActivity.this).getNoPosterAidList();
            if(noPosterRecordList != null && noPosterRecordList.size() > 0){
                new RequestAlbumInfoTask(PlayHistoryActivity.this, noPosterRecordList, "record").start();
            }
            playRecordList = new PlayRecordDao(PlayHistoryActivity.this).getAll();
            if (playRecordList.size() == 0) {
                showNoData();
            } else {
                showList();
                setNoMore();
                mAdapter.refreshPlayList(playRecordList);
            }
        }
    }

    @Override
    public boolean onRequestFailed() {
        myProgressDialog.dismiss();
        try {
            ArrayList<Episode> epList = (ArrayList<Episode>) mCache.getAsObject(currplayRecord.getAid() + currplayRecord.getSite() + currplayRecord.getRequestType());
            if (epList != null && epList.size() != 0) {
                LogUtils.i(TAG, "请求失败，获取本地播放页缓存");
                jumpToPlayActivity(epList);
            } else {
                UIs.showToast("获取剧集信息失败，请检查网络链接");
            }
        } catch (Exception e) {
            mCache.remove(currplayRecord.getAid() + currplayRecord.getSite() + currplayRecord.getRequestType());
        }
        return false;
    }


    @Override
    public void onRequestSuccess(int updateId, VideoDataBean result) {
        myProgressDialog.dismiss();
        if (result.getPlaySrcBean().getEpisodes().size() == 0) {
            onRequestFailed();
            return;
        }
        jumpToPlayActivity(result);
    }

    @Override
    public void onPreRequest() {
        myProgressDialog.show();
    }

    private void jumpToPlayActivity(VideoDataBean result) {
        PlayData playData = new PlayData(currplayRecord, null, UmengEventPoster.PLAYER_FROM_HISTORY);
        playData.setmPorderLists(result.getmPorderLists());
        playData.setmViewName(result.getName());
        playData.setSrc(result.getSrc());
        playData.setCategory(result.getCategory());
        playData.setAreaname(result.getAreaname());
        playData.setSubcategoryname(result.getSubcategoryname());
        playData.setYear(result.getYear());
        Intent intent = new Intent(this, PlayActivitySelfOwn.class);
        Bundle b = new Bundle();
        b.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(b);
        this.startActivity(intent);
    }

    private void jumpToPlayActivity(ArrayList<Episode> epList) {
        PlayData playData = new PlayData(currplayRecord, epList, UmengEventPoster.PLAYER_FROM_HISTORY);
        Intent intent = new Intent(this, PlayActivitySelfOwn.class);
        Bundle b = new Bundle();
        b.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(b);
        this.startActivity(intent);
    }

    /**
     * 判断当前URL是否是本地的URL
     *
     * @param url
     * @return zhangshuo
     * 2014年6月12日 下午2:24:34
     */
    private boolean isLocalUrl(String url) {
        String prefix = "file:///";
        return !TextUtils.isEmpty(url) && url.startsWith(prefix);
    }


    public void setTitle() {
        showUserSelecedItem(mAdapter.deletedNum);
    }


    private void showUserSelecedItem(int deleteNum) {

        String deleteContent = "";
        String allSelectContent = "";
        if (deleteNum != 0) {//没有全部删除
            if (deleteNum == mAdapter.getCount()) {
                allSelectContent = getString(R.string.deselect_all);
            } else {
                allSelectContent = getString(R.string.check_all);
            }
            deleteContent = getString(R.string.delete_up) + "(" + deleteNum + ")";
        } else {

            deleteContent = getString(R.string.delete_up);
            allSelectContent = getString(R.string.check_all);
        }


        allSelect.setText(allSelectContent);
        mConfirm_delete.setText(deleteContent);
        mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
        mAdapter.notifyDataSetChanged();

    }

    private void deleteTip() {
        try {
            Builder builder = new Builder(this);
            builder.setTitle(R.string.tip);
            int deletingCount = mAdapter.deletedNum;
            String deleteTipContent = getString(R.string.delete_up) + deletingCount + getString(R.string.num_playhistory);
            builder.setMessage(deleteTipContent);
            builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MoviesConstant.isRefreshMyFragment = true;
                    playHistroySelectDelete();

                }
            });
            builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Dialog dialog = builder.create();
            dialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除所有选中的选项
    private void playHistroySelectDelete() {
        MoviesConstant.isRefreshMyFragment = true;
        PlayRecordDao playRecordDao = mAdapter.playRecordDao;
        List<PlayRecord> list = mAdapter.playHistroyList;
        ArrayList<Boolean> bools = mAdapter.mChecked;
        int size = bools.size();
        int deleteNum = 0;
        List<PlayRecord> deleteList = new ArrayList<PlayRecord>();
        for (int pos = 0; pos < size; pos++) {
            if (bools.get(pos - deleteNum)) {//选中状态
                if(pos - deleteNum < list.size()){
                    deleteList.add(list.get(pos - deleteNum));
                    playRecordDao.delete(list.get(pos - deleteNum).getAid());
                    list.remove(pos - deleteNum);
                    bools.remove(pos - deleteNum);
                    mAdapter.deletedNum--;

                    deleteNum++;
                }

            }
        }
        if(deleteList.size() > 0){
            if(TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))){
//                playRecordDao.batchDelete(deleteList);
            }else{
                RequestDoPlayRecordTask requestDoPlayRecordTasknew = new RequestDoPlayRecordTask(this, deleteList, "delete");
                requestDoPlayRecordTasknew.setRequestListener(new PlayRecordListListener());
                requestDoPlayRecordTasknew.start();
            }
        }

        mConfirm_delete.setText(R.string.delete_up);
        mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
        this.mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

            case R.id.confirm_delete:
                if (null != mAdapter) {
                    if (mAdapter.isEditing) {
                        if (mAdapter.deletedNum > 0) {
                            deleteTip();
                        }
                    }
                }

                break;
            case R.id.all_select:
                if (mAdapter.deletedNum == mAdapter.getCount()) {//全选之后再点击取消全选
                    MoviesConstant.isRefreshMyFragment = true;
                    allSelect.setText(R.string.check_all);
                    mAdapter.changleAllSelectState();

                } else {
                    allSelect.setText(R.string.deselect_all);
                    mAdapter.changleAllSelectState();
                }

                playHistroyAllSelected();

                mAdapter.notifyDataSetChanged();

                break;
        }
    }

    private void playHistroyAllDiselected() {
        MoviesConstant.isRefreshMyFragment = true;
        for (int i = 0; i < mAdapter.mChecked.size(); i++) {
            mAdapter.mChecked.set(i, false);
        }
        mAdapter.deletedNum = 0;

    }

    private void playHistroyAllSelected() {
        MoviesConstant.isRefreshMyFragment = true;
        if (mAdapter.deletedNum != mAdapter.getCount()) {
            String content = getString(R.string.delete_up) + "(" + mAdapter.getCount() + ")";
            mConfirm_delete.setText(content);
            mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
            for (int i = 0; i < mAdapter.getCount(); i++) {
                mAdapter.mChecked.add(i, true);
            }
            mAdapter.deletedNum = mAdapter.getCount();
        } else {

            mConfirm_delete.setText(R.string.delete_up);
            mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
            // 用户选择取消全选则用户当前选中项为0
            mAdapter.deletedNum = 0;
            for (int i = 0; i < mAdapter.mChecked.size(); i++) {
                mAdapter.mChecked.set(i, false);
            }
            mAdapter.deletedNum = 0;
        }
    }

    /**
     * 请求剧集信息
     *
     * @author daipei
     */
    private class RequestVideoDataTask extends MoviesHttpAsyncTask<VideoDataBean> {

        @Override
        public void netNull() {
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
        }

        public RequestVideoDataTask(Context context) {
            super(context);
        }

        @Override
        public LVideoDataHull<VideoDataBean> doInBackground() {
            LVideoDataHull<VideoDataBean> ret = MoviesHttpApi.requestVideoData(new VideoDetailParser(), currplayRecord.getAid(), "");
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, VideoDataBean result) {
            if (null != result) {
                requestEpisodesTask.setParams(currplayRecord.getSite(), currplayRecord.getAid(), result);
                if (!requestEpisodesTask.isCancelled()) {
                    requestEpisodesTask.cancel();
                }
                requestEpisodesTask.start();
            }

        }
    }

    private class PlayRecordOnRefreshListener extends MyOnRefreshListner {

        @Override
        protected void onLoadMoreData() {
            if (hasMore) {
                if (mRequestUserPlayRecordsTask != null) {
                    if (!mRequestUserPlayRecordsTask.isCancelled()) {
                        mRequestUserPlayRecordsTask.cancel();
                        mRequestUserPlayRecordsTask = null;
                    }
                }
                mRequestUserPlayRecordsTask = new RequestUserPlayRecordsTask(PlayHistoryActivity.this, index, LIMIT);
                mRequestUserPlayRecordsTask.setRequestListener(mPlayRecordListListener);
                mRequestUserPlayRecordsTask.start();
            } else {
                handler.sendEmptyMessageDelayed(0, 50);
            }
        }

        @Override
        protected void onRefreshData() {
            index = 0;
            if (mRequestUserPlayRecordsTask != null) {
                if (!mRequestUserPlayRecordsTask.isCancelled()) {
                    mRequestUserPlayRecordsTask.cancel();
                    mRequestUserPlayRecordsTask = null;
                }
            }
            mRequestUserPlayRecordsTask = new RequestUserPlayRecordsTask(PlayHistoryActivity.this, index, LIMIT);
            mRequestUserPlayRecordsTask.setRequestListener(mPlayRecordListListener);
            mRequestUserPlayRecordsTask.start();
        }

    }

    private void resetHasMore() {
        hasMore = true;
        list.setLoadingDrawable(
                getResources().getDrawable(R.drawable.default_ptr_rotate),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setRefreshingLabel(getString(R.string.loading),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setReleaseLabel(getString(R.string.release_loadmore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setPullLabel(getString(R.string.pull_loadmore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
    }

    private void setNoMore() {
        hasMore = false;
        list.setLoadingDrawable(
                getResources().getDrawable(R.drawable.transparent),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setRefreshingLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setReleaseLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        list.setPullLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
    }

    /**
     * 分页请求播放记录的监听
     */
    private class PlayRecordListListener implements RequestCommonInterface{

        @Override
        public void requestSuccess(int updateId, Object data, String name) {
            root.finish();
            if(name.equals(MoviesHttpApi.USER_PLAY_LIST)){
                total = ((PlayRecordList)data).getTotal();
                if(index == 0){
                    playRecordList = ((PlayRecordList) data).getPlayRecordList();
                }else{
                    playRecordList.addAll(((PlayRecordList) data).getPlayRecordList());
                }
                if(playRecordList.size()==0){
                    showNoData();
                }else{
                    if(index + LIMIT < total){
                        index = index + LIMIT;
                        resetHasMore();
                    }else{
                        setNoMore();
                    }
                    if(isShowButtom){
                        mRightFirstTv.setText("完成");
                        currentState = State.EDITING;
                        editLayout.setVisibility(View.VISIBLE);
                    }
                    showList();
                    mAdapter.refreshPlayList(playRecordList);
                    list.onRefreshComplete();
                }
                setTitle();
            }else if(name.equals(MoviesHttpApi.DO_PLAY_RECORD)){
                if(0 == mAdapter.playHistroyList.size()) {
                    index = 0;
                    if (mRequestUserPlayRecordsTask != null) {
                        if (!mRequestUserPlayRecordsTask.isCancelled()) {
                            mRequestUserPlayRecordsTask.cancel();
                            mRequestUserPlayRecordsTask = null;
                        }
                    }
                    mRequestUserPlayRecordsTask = new RequestUserPlayRecordsTask(PlayHistoryActivity.this, index, LIMIT);
                    mRequestUserPlayRecordsTask.setRequestListener(mPlayRecordListListener);
                    mRequestUserPlayRecordsTask.start();
                }
            }else{

            }
        }

        @Override
        public void requestFail(String name) {
            root.finish();
            root.error(false, false);
        }

        @Override
        public void netError(String name) {
            root.finish();
            root.error(false, false);
        }
    }
}